package com.nepxion.discovery.agent;

/**
 * <p>Title: Nepxion Discovery</p>
 * <p>Description: Nepxion Discovery</p>
 * <p>Copyright: Copyright (c) 2017-2050</p>
 * <p>Company: Nepxion</p>
 * @author zifeihan
 * @version 1.0
 */

import java.lang.instrument.Instrumentation;

import com.nepxion.discovery.agent.callback.TransformTemplate;
import com.nepxion.discovery.agent.logger.AgentLogger;
import com.nepxion.discovery.agent.plugin.PluginFinder;
import com.nepxion.discovery.agent.transformer.DispatcherClassFileTransformer;

/**
 * 参考博文:https://blog.csdn.net/u012410733/article/details/104878111 基于 Java Agent 实现零倾入监控
 * https://www.cnblogs.com/jackion5/p/10771609.html 基于Javaagent技术实现字节码增强及Instrumentation接口详解
 * https://carlzone.blog.csdn.net/article/details/111405081 Nepxion Discovery 之 Discovery Agent 解决异步场景线程 ThreadLocal 上下文丢失问题
 * https://segmentfault.com/a/1190000037602678 JavaAgent详细原理(重要)
 * https://www.cnblogs.com/takumicx/p/10150344.html SpringBoot中使用LoadTimeWeaving技术实现类加载期间的AOP功能
 *
 * https://www.cnblogs.com/grey-wolf/p/12228958.html (重要)AspectJ的运行时织入（Load-Time-Weaving），基本内容是讲清楚了（附源码）
 * https://www.cnblogs.com/grey-wolf/p/12283544.html
 */
public class DiscoveryAgent {
    private final static AgentLogger LOG = AgentLogger.getLogger(DiscoveryAgent.class.getName());

    public static void premain(String agentArgs, Instrumentation instrumentation) {
        LOG.info(String.format("%s agent on load, version %s", DiscoveryAgent.class.getSimpleName(), DiscoveryAgentConstant.DISCOVERY_AGENT_VERSION));

        TransformTemplate transformTemplate = new TransformTemplate();
        PluginFinder.load(transformTemplate);

        instrumentation.addTransformer(new DispatcherClassFileTransformer(transformTemplate));

        System.setProperty(DiscoveryAgentConstant.SPRING_APPLICATION_DISCOVERY_AGENT_VERSION, DiscoveryAgentConstant.DISCOVERY_AGENT_VERSION);
    }
}
